package com.aiti.lulian.service.impl;

import com.aiti.base.core.base.service.iml.BaseSerivceImpl;
import com.aiti.base.core.page.PageInfo;
import com.aiti.base.core.page.PageResult;
import com.aiti.base.core.utils.message.Message;
import com.aiti.lulian.dto.CardPromotionSubDto;
import com.aiti.lulian.entity.crad.promotion.CardPromotionSub;
import com.aiti.lulian.mapper.promotion.CardPromotionSubMapper;
import com.aiti.lulian.service.ICardPromotionSubService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

@Service
public class CardPromotionSubServiceImpl extends BaseSerivceImpl<CardPromotionSubMapper, CardPromotionSub> implements ICardPromotionSubService {

    private final CardPromotionSubMapper baseMapper;

    public CardPromotionSubServiceImpl(CardPromotionSubMapper baseMapper) {
        this.baseMapper = baseMapper;
    }

    @Override
    public Message promotionSubList(Page page, CardPromotionSubDto dto) {
        LambdaQueryWrapper<CardPromotionSub> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(CardPromotionSub::getPkId,dto.getPkId()).isNull(CardPromotionSub::getDeleteTime).orderByDesc(CardPromotionSub::getBaseCreateTime);
        Page page1 = this.page(page, wrapper);
        PageResult rspData = new PageResult(page1.getRecords(), new PageInfo(dto.getPageNum(), dto.getPageSize()), page1.getTotal());
        return Message.success(rspData);
    }

    @Override
    public Message deletePromotionSub(String baseId) {
        CardPromotionSub promotionSub = this.getById(baseId);
        if(promotionSub != null){
            BigDecimal cumulativeGain = promotionSub.getCumulativeGain();
            if(cumulativeGain != null && cumulativeGain.compareTo(BigDecimal.ZERO) > 0){
                return Message.fail("该推广计划已累计收益，无法删除");
            }else{
                LambdaUpdateWrapper<CardPromotionSub> wrapper = new LambdaUpdateWrapper<>();
                wrapper.set(CardPromotionSub::getDeleteTime, new Date()).eq(CardPromotionSub::getBaseId,baseId);
                this.update(wrapper);
                return Message.success();
            }
        }else{
            return Message.success();
        }
    }

    @Override
    public int removePromotionSubByAccounts(List<String> originalAccounts) {
        return baseMapper.deletePromotionSubByAccounts(originalAccounts);
    }
}